/**
 * 初始化主题
 */
import {watch} from "vue";
import store from "../store";
import {THEME_DARK, THEME_LIGHT, THEME_SYSTEM} from "../constants";

/**
 * 监听系统主题变更
 */
let matchMedia
const watchSystemThemeChange = () => {
    //仅需一次初始化
    if (matchMedia) return
    matchMedia = window.matchMedia('(prefers-color-scheme:dark)')
    //监听主题变化
    matchMedia.onchange = () => {
        changeTheme(THEME_SYSTEM)
    }
}
const changeTheme = (theme) => {
    //html 的class
    let themeClassName = ''
    switch (theme) {
        case THEME_LIGHT:
            themeClassName = 'light'
            break
        case THEME_DARK:
            themeClassName = 'dark'
            break
        case THEME_SYSTEM:
            //调用方法，监听系统主题变化
            watchSystemThemeChange()
            themeClassName = matchMedia.matches ? 'dark' : 'light'
            break
        default:
            themeClassName = 'light'
    }
    //修改className
    document.querySelector('html').className = themeClassName
}
export default () => {
    // 1.当主题发生改变时,或者进入系统时 可以进行html class的配置
    watch(() => store.getters.themeType, (val) => {
        changeTheme(val)
    }, {
        //初始化时执行一次
        immediate: true
    })
}